package com.wangbo.rabbit;

import com.wangbo.rabbit.util.JacksonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

@Component
@Slf4j
public class RabbitProducer {
    @Resource
    private RabbitTemplate rabbitTemplate;

    private volatile boolean available = true;

    public void sendMessage(String exchangeName, String routingKey, RabbitMessage rabbitMessage) {
        // 消息ID
        String messageId = String.valueOf(rabbitMessage.getMessageId());
        // 消息体
        String payload = JacksonUtil.toJson(rabbitMessage);
        try {
            rabbitTemplate.convertAndSend(exchangeName, routingKey, payload, (message) -> {
                message.getMessageProperties().setMessageId(messageId);
                return message;
            }, new CorrelationData(messageId));
        } catch (Exception e) {
            log.info("连接异常，发送失败，消息保存到文件");
        }
    }
}
